import paho.mqtt.client as mqtt
from time import sleep
import json
import time
import random
import threading


def publishVoice(n, sn, i):
    global ids
    client = mqtt.Client()
    client.username_pw_set('CMAC692000004957REP8YnS', 'ji6LeXKg')
    client.connect('so2.airphone.vip', 1883, 5)
    price_yuan = random.randrange(0, 9999)
    price_point = random.randrange(10, 99)
    if n == 1:
        ids = 'A213-A215-A' + str(random.randrange(107, 212)) + '-A134-A72-A' + str(
            random.randrange(107, 212)) + '-A' + str(random.randrange(186, 212)) + '-B' + str(random.randrange(1, 106))
    price = str(price_yuan) + "." + str(price_point)
    json_data = {"msg_id": str(price_yuan), "sn": "97001100000291", "expires": str(time.time()), "create_time":
        str(time.time()),
                 "create_time_milli": str(round(time.time() * 1000)),
                 "data": {"order_info": 1, "pay_price": price, "pay_status": 1, "pay_type": 1, "finishtime": "",
                          "createtime": ""}, "light": "g500-8000", "ids": ids}
    print(json.dumps(json_data, indent=4))
    client.publish('/iot/message/' + sn, payload=f'{json.dumps(json_data)}', qos=0)
    print(f"第{i + 1}次" + str(time.strftime("%H:%M:%S")) + "推送成功")


sn = str(input("请复制要推送的sn："))
n = int(input("请选择（1为随机产生语音指令，2为自定义指令）："))
if n == 2:
    ids = str(input("请输入要固定推送的语音指令（A213-A215-B99）："))
num = int(input('请输入要测试的总次数：'))
j = int(input("请输入要并发的数量（比如一秒推送多少单）："))
timer = int(input('请输入间隔并发的秒数：'))
i = 0
while True:
    if i == num:
        break
    for k in range(j):
        t = threading.Thread(target=publishVoice, args=(n, sn, i))
        i += 1
        t.start()
        t.join()
    sleep(timer)

sleep(30)
